package com.lin.manager.login.service.impl;

import com.lin.manager.common.ex.BizException;
import com.lin.manager.login.service.SysLoginService;
import com.lin.manager.secure.model.SecurityUser;
import com.lin.manager.secure.token.AccessTokenService;
import com.lin.manager.login.model.vo.LoginUserVo;
import com.lin.manager.system.service.SysUserRoleService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @作者: 林江
 * @创建时间: 2024/3/15
 * @功能:
 */
@Service
public class LoginServiceImpl implements SysLoginService {
    @Resource
    private SysUserRoleService userRoleService;
    @Resource
    private AccessTokenService accessTokenService;

    @Override
    public LoginUserVo getUserInfo(String token) {
        SecurityUser user = accessTokenService.getUserByToken(token);
        if (Objects.nonNull(user)) {
            // 查询权限
            LoginUserVo userVo = this.findLoginRoleByUserId(user.getId());
            userVo.setName(user.getName());
            userVo.setPhone(user.getPhone());
            userVo.setUsername(user.getUsername());
            return userVo;
        }
        throw new BizException("解析token失败");
    }

    @Override
    public void logout() {
        SecurityContextHolder.getContext().setAuthentication(null);
    }

    /**
     * 获取登录用户的权限和角色
     *
     * @param userId
     * @return
     */
    private LoginUserVo findLoginRoleByUserId(Long userId) {
        // 权限和角色
        LoginUserVo userVo = userRoleService.findLoginRoleByUserId(userId);
        return userVo;
    }

}
